package com.company.loganalyzer.utils;

import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 时间范围工具类
 * 
 * 处理时间范围解析和索引名称生成
 */
@Slf4j
public class TimeRangeUtils {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd");
    private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss");

    /**
     * 根据时间范围生成ES索引名称列表
     * 
     * @param indexPattern 索引模式前缀（如 "cloud_api-"）
     * @param timeRange 时间范围
     * @return 索引名称列表
     */
    public static List<String> generateIndexNames(String indexPattern, String timeRange) {
        List<String> indexNames = new ArrayList<>();
        
        try {
            if (timeRange == null || timeRange.trim().isEmpty()) {
                // 默认查询今天的索引
                indexNames.add(indexPattern + LocalDate.now().format(DATE_FORMATTER));
                return indexNames;
            }

            // 解析时间范围
            if (timeRange.contains("~")) {
                // 范围查询：2024.01.15~2024.01.16
                String[] parts = timeRange.split("~");
                if (parts.length == 2) {
                    LocalDate startDate = LocalDate.parse(parts[0].trim(), DATE_FORMATTER);
                    LocalDate endDate = LocalDate.parse(parts[1].trim(), DATE_FORMATTER);
                    
                    LocalDate current = startDate;
                    while (!current.isAfter(endDate)) {
                        indexNames.add(indexPattern + current.format(DATE_FORMATTER));
                        current = current.plusDays(1);
                    }
                }
            } else if (timeRange.matches("\\d{4}\\.\\d{2}\\.\\d{2}")) {
                // 单日查询：2024.01.15
                indexNames.add(indexPattern + timeRange);
            } else {
                // 相对时间范围
                LocalDate today = LocalDate.now();
                switch (timeRange.toLowerCase()) {
                    case "today":
                    case "last_1d":
                        indexNames.add(indexPattern + today.format(DATE_FORMATTER));
                        break;
                    case "yesterday":
                        indexNames.add(indexPattern + today.minusDays(1).format(DATE_FORMATTER));
                        break;
                    case "last_3d":
                        for (int i = 0; i < 3; i++) {
                            indexNames.add(indexPattern + today.minusDays(i).format(DATE_FORMATTER));
                        }
                        break;
                    case "last_7d":
                    case "last_week":
                        for (int i = 0; i < 7; i++) {
                            indexNames.add(indexPattern + today.minusDays(i).format(DATE_FORMATTER));
                        }
                        break;
                    case "last_30d":
                    case "last_month":
                        for (int i = 0; i < 30; i++) {
                            indexNames.add(indexPattern + today.minusDays(i).format(DATE_FORMATTER));
                        }
                        break;
                    default:
                        // 默认查询今天
                        indexNames.add(indexPattern + today.format(DATE_FORMATTER));
                        log.warn("未识别的时间范围: {}, 使用默认值（今天）", timeRange);
                }
            }
        } catch (DateTimeParseException e) {
            log.error("时间范围解析失败: {}", timeRange, e);
            // 出错时默认查询今天
            indexNames.add(indexPattern + LocalDate.now().format(DATE_FORMATTER));
        }

        return indexNames;
    }

    /**
     * 解析时间范围为开始和结束时间
     * 
     * @param timeRange 时间范围
     * @return [startTime, endTime]
     */
    public static LocalDateTime[] parseTimeRange(String timeRange) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start, end;

        try {
            if (timeRange == null || timeRange.trim().isEmpty()) {
                // 默认最近1小时
                start = now.minusHours(1);
                end = now;
            } else if (timeRange.contains("~")) {
                // 范围查询：2024.01.15~2024.01.16
                String[] parts = timeRange.split("~");
                if (parts.length == 2) {
                    start = LocalDate.parse(parts[0].trim(), DATE_FORMATTER).atStartOfDay();
                    end = LocalDate.parse(parts[1].trim(), DATE_FORMATTER).atTime(23, 59, 59);
                } else {
                    start = now.minusHours(1);
                    end = now;
                }
            } else if (timeRange.matches("\\d{4}\\.\\d{2}\\.\\d{2}")) {
                // 单日查询：2024.01.15
                LocalDate date = LocalDate.parse(timeRange, DATE_FORMATTER);
                start = date.atStartOfDay();
                end = date.atTime(23, 59, 59);
            } else {
                // 相对时间范围
                switch (timeRange.toLowerCase()) {
                    case "last_1h":
                        start = now.minusHours(1);
                        end = now;
                        break;
                    case "last_3h":
                        start = now.minusHours(3);
                        end = now;
                        break;
                    case "last_6h":
                        start = now.minusHours(6);
                        end = now;
                        break;
                    case "last_12h":
                        start = now.minusHours(12);
                        end = now;
                        break;
                    case "last_24h":
                    case "today":
                    case "last_1d":
                        start = now.minusDays(1);
                        end = now;
                        break;
                    case "yesterday":
                        start = now.minusDays(1).withHour(0).withMinute(0).withSecond(0);
                        end = now.minusDays(1).withHour(23).withMinute(59).withSecond(59);
                        break;
                    case "last_3d":
                        start = now.minusDays(3);
                        end = now;
                        break;
                    case "last_7d":
                    case "last_week":
                        start = now.minusDays(7);
                        end = now;
                        break;
                    case "last_30d":
                    case "last_month":
                        start = now.minusDays(30);
                        end = now;
                        break;
                    default:
                        start = now.minusHours(1);
                        end = now;
                        log.warn("未识别的时间范围: {}, 使用默认值（最近1小时）", timeRange);
                }
            }
        } catch (DateTimeParseException e) {
            log.error("时间范围解析失败: {}", timeRange, e);
            start = now.minusHours(1);
            end = now;
        }

        return new LocalDateTime[]{start, end};
    }

    /**
     * 格式化时间为字符串
     */
    public static String formatDateTime(LocalDateTime dateTime) {
        return dateTime.format(DATETIME_FORMATTER);
    }

    /**
     * 格式化日期为字符串
     */
    public static String formatDate(LocalDate date) {
        return date.format(DATE_FORMATTER);
    }
}